<?php

namespace app\home\controller;

use think\Cookie;
use think\Db;

class User extends Base
{
    //获取用户信息
    public function userInfo()
    {
        //获取用户的基本信息
        $userInfo = Db::name('user')->where(['id' => $this->user['id']])->field("id uid,nickname,head_img_url,mobile")->find();
        //查询今日和累计赚取余额
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        //用户等级
        $leves = [
            100 => '青铜',
            500 => '白银',
            1000 => '黄金',
            1000000000 => '钻石'
        ];
        foreach ($leves as $k => $val) {
            if ($userEarn['totalearned'] < $k) {
                $level = $val;
                break;
            }
        }
        return outputJson(0, 'ok', ['user_info' => $userInfo, 'userEarn' => $userEarn, 'level' => $level]);
    }

    //提现页面
    public function withdrawalPage()
    {
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        $aliConfig = [
            'aliid' => $this->user['aliid'],
            'aliname' => $this->user['aliname']
        ];
        return outputJson(0, 'ok', ['money' => $userEarn['money'], 'aliConfig' => $aliConfig]);
    }

    //提现
    public function withdrawal()
    {
        $data = input('post.');
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        if ($data['account'] > $userEarn['money']) {
            return outputJson(100, '提现金额不能大于余额');
        }
        if (!$data['aliid']) {
            return outputJson(100, '支付宝账户名不能为空');
        }
        if (!$data['aliname']) {
            return outputJson(100, '支付宝账号不能为空');
        }
        //修改支付宝提现配置
        if ((!$this->user['aliid'] && !$this->user['aliname']) || $this->user['aliid'] != $data['aliid'] || $this->user['aliname'] != $data['aliname']) {
            Db::name('user')->where(['id' => $this->user['id']])->update(['aliid' => $data['aliid'], 'aliname' => $data['aliname']]);
        }
        //徒弟提现
        $result = withdrawal(config('urls') . '/pay/alipay', $this->user['id'], ($data['account'] * 100), $data['aliid'], $data['aliname']);
        if ($result['errcode'] != 0) {
            return outputJson(100, $result['errmsg']);
        }
        if ($this->user['istixian'] == 0) {
            //新手任务----第一次提现发放奖励
            $signin = dailyTasks(config('urls') . '/account/addaccount', '完成一次提现', $this->user['id'], 20);
            if (!$signin) {
                return outputJson(100, 'fail');
            }
            Db::name('user')->where('id', $this->user['id'])->update(['istixian' => 1]);
        }
        return outputJson(0, 'ok');
    }

    //提现记录
    public function withdrawalLog()
    {
        $log = withdrawalLog(config('urls') . '/pay/txlog', $this->user['id']);
        $list = $log['data']['tx'] ? object_arrays(json_decode($log['data']['tx'])) : [];
        foreach ($list as $k => $val) {
            $list[$k]['integral'] = sprintf("%.2f", ($val['integral'] / 100));
        }
        return outputJson(0, 'ok', ['list' => $list]);
    }

    //收入信息
    public function incomelog()
    {
        $userEarn = incomelog(config('urls') . '/account/incomelog', $this->user['id']);
        $list = $userEarn['income'];
        if ($userEarn['income']) {
            $list = object_arrays(json_decode($userEarn['income']));
            if(input('rtype') && input('rtype') == 1000){
                foreach ($list as $k => $val) {
                    if($val['rtype'] < 991 || $val['rtype'] >1000){
                        unset($list[$k]);
                        continue;
                    }
                    $list[$k]['integral'] = sprintf("%.2f", ($val['integral'] / 100));
                    $list[$k]['status'] = $val['rtype'] == 1000 ? 0 : 1;
                }
                $list = array_values($list);
            }else{
                foreach ($list as $k => $val) {
                    $list[$k]['integral'] = sprintf("%.2f", ($val['integral'] / 100));
                    $list[$k]['status'] = $val['rtype'] == 1000 ? 0 : 1;
                }
            }
        }
        return outputJson(0, 'ok', ['list' => $list]);
    }

    //邀请记录
    public function inviteRewardsLog()
    {
        $result = Db::name('invite_rewards_log')->where(['master_id' => $this->user['id']])->select();
        foreach ($result as $k => $val) {
            $result[$k]['goggles'] = sprintf("%.2f", ($val['goggles'] / 100));
        }
        return outputJson(0, 'ok', ['code' => $this->user['id'], 'list' => $result, 'codeimg' => $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . '/uploads/qcodes.png']);
    }

    //徒弟提现记录
    public function tudilog()
    {
        $uid = input('disciple_id');
        $tudilog = incomelog(config('urls') . '/account/tudilog', $uid);
        $list = [];
        if ($tudilog['tx']) {
            $list = object_arrays(json_decode($tudilog['tx']));
            foreach ($list as $k => $val) {
                $list[$k]['integral'] = sprintf("%.2f", ($val['integral'] / 100));
            }
        }
        return outputJson(0, 'ok', ['list' => $list]);
    }

    //填写邀请码
    public function inviteRewards()
    {
        $inviteCode = input('inviteCode');
        if ($inviteCode == $this->user['id']) {
            return outputJson(100, '请填写有效的邀请码');
        }
        //判断是否填写过邀请码
        $invite = Db::name('user')->where('id', $this->user['id'])->value('invite_code');
        if ($invite) {
            return outputJson(100, '已填写过邀请码');
        }
        //查询邀请码用户的id
        $inviteId = Db::name('user')->where(['id' => $inviteCode])->value('id');
        if (!$inviteId) {
            return outputJson(100, '邀请码不存在');
        }
        //增加邀请码用户的奖励
        $inviteRewards = inviteRewards(config('urls') . '/account/addaccount', $inviteId);
        if (!$inviteRewards) {
            return outputJson(100, 'fail');
        }
        //增加当前用户的邀请码
        $result = Db::name('user')->where('id', $this->user['id'])->update(['invite_code' => $inviteCode]);
        //增加邀请码用户的奖励记录
        $inviteRewardsLog = Db::name('invite_rewards_log')->where(['master_id' => $inviteId, 'disciple_id' => $this->user['id']])->find();
        if (!$inviteRewardsLog) {
            $results = Db::name('invite_rewards_log')->insert(['master_id' => $inviteId, 'disciple_id' => $this->user['id'], 'invite_rewards' => '+1元（已发）', 'add_time' => date('Y-m-d H:i:s')]);
        } else {
            $results = Db::name('invite_rewards_log')->where(['master_id' => $inviteId, 'disciple_id' => $this->user['id']])->update(['invite_rewards' => '+1元（已发）']);
        }
        if ($result === false || $results === false) {
            return outputJson(100, 'fail');
        }

        //填写好邀请码发放奖励
        $signin = dailyTasks(config('urls') . '/account/addaccount', '填写邀请码', $this->user['id'], 20);
        if (!$signin) {
            return outputJson(100, 'fail');
        }

        return outputJson(0, 'ok');
    }

    //设置手机号
    public function setMobile()
    {
        $mobile = input('mobile');
        $code = input('code');
        //验证短信验证码
        $codes = Db::name('log')->where(['uid' => $this->user['id'], 'mobile' => $mobile, 'status' => 0, 'code' => $code])->find();
        if (!$codes) {
            return outputJson(100, '验证码错误', $codes);
        }
        $data = Db::name('user')->where(['id' => $this->user['id']])->update(['mobile' => $mobile]);
        if ($data === false) {
            return outputJson(100, 'fail', $codes);
        } else {
            //改变短信状态  表示
            Db::name('log')->where(['uid' => $this->user['id'], 'mobile' => $mobile, 'status' => 0])->update(['status' => 1]);
            //设置手机好成功发放奖励
            $signin = dailyTasks(config('urls') . '/account/addaccount', '设置手机号', $this->user['id'], 20);
            if (!$signin) {
                return outputJson(100, 'fail');
            }
            return outputJson(0, 'ok');
        }
    }

    //发送短信
    public function sendMsg()
    {
        $mobile = input('mobile');
        $code = mt_rand(100000, 999999);
        $result = sendAliyunSms($mobile, $code);
        if ($result['code'] == "OK") {
            Db::name('log')->insert(['uid' => $this->user['id'], 'mobile' => $mobile, 'code' => $code, 'status' => 0]);
            Db::name('log')->getLastSql();
            return outputJson(0, 'ok');
        } else {
            return outputJson(100, 'fail');
        }
    }

    //查询悬赏记录列表
    public function queryRewardLog()
    {
        $where['uid'] = $this->user['id'];
        $statuslist = [
            1 => [1],
            2 => [2],
            3 => [3],
            4 => [4],
            5 => [5],
            6 => [6, 9, 10, 11],
            7 => [8],
        ];
        if (input('status')) {
            $where['status'] = ['in', $statuslist[input('status')]];
        }
        $list = Db::name('task_receive')->where($where)->field('task_id id,title,add_time,unit_price')->select();
        return outputJson(0, 'ok', $list);
    }

//    //获取悬赏记录任务的详情
//    public function taskDetail()
//    {
//        $res = Db::name('task_receive')->where(['id'=>$this->user['id'],'task_id' => input('id')])->field('task_id id,abstract,title,unit_price,add_time,status,num')->find();
//        //倒计时处理
//        $res['count_down'] = time() - strtotime($res['add_time']);
//        return outputJson(0, 'ok', $res);
//    }

    //审核任务管理列表
    public function taskAudit()
    {
        $list = Db::name('task_release')->alias('a')
            ->join('tp_task_receive b', 'a.id = b.task_id', 'left')
            ->join('tp_user c', 'c.id = b.uid', 'left')
            ->field('b.id,b.title,b.status,b.add_time,b.unit_price,c.nickname')
            ->where(['a.uid' => $this->user['id'], 'b.status' => input('status'), 'a.type' => 2])
            ->select();
        return outputJson(0, 'ok', ['list' => $list]);
    }

    //接取任务的审核
    public function subTaskAudit()
    {
        $uid  = Db::name('task_receive')->where(['id' => input('id')])->value('uid');
        //通过审核
        if (input('type') == 1) {
            $taskReceive = Db::name('task_receive')->where(['id' => input('id'), 'status' => ['eq', 3]])->select();
            if (count($taskReceive) == 1) {
                //新手任务----完成一次悬赏任务
                $signin = dailyTasks(config('urls') . '/account/addaccount', '完成一次悬赏任务', $uid, 20);
                if (!$signin) {
                    return outputJson(100, 'fail');
                }
            }
            $info['status'] = 3;
            $info['audit_time'] = date('Y-m-d H:i:s');
        } else {
            $info['status'] = 4;
            $info['audit_refuse_reason'] = input('audit_refuse_reason');
            $info['audit_refuse_time'] = date('Y-m-d H:i:s');
        }
        $result = Db::name('task_receive')->where(['id' => input('id')])->update($info);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        updateredis(config('xsurls') . '/job/updateredis', $uid);
        return outputJson(0, 'ok');
    }

    //任务申诉理由填写
    public function subTaskAppleReason()
    {
        $info['status'] = 5;
        $info['appeal_reason'] = input('appeal_reason');
        $info['appeal_reason_time'] = date('Y-m-d H:i:s');
        $result = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update($info);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
        return outputJson(0, 'ok');
    }

    //任务申诉处理
    public function subTaskApple()
    {
        $uid  = Db::name('task_receive')->where(['id' => input('id')])->value('uid');
        //申述成功
        if (input('type') == 1) {
            $taskReceive = Db::name('task_receive')->where(['id' => input('id'), 'status' => ['eq', 3]])->select();
            if (count($taskReceive) == 1) {
                //新手任务----完成一次悬赏任务
                $signin = dailyTasks(config('urls') . '/account/addaccount', '完成一次悬赏任务', $uid, 20);
                if (!$signin) {
                    return outputJson(100, 'fail');
                }
            }
            $info['status'] = 3;
            $info['audit_time'] = date('Y-m-d H:i:s');
        } else {
            $info['status'] = 8;
            $info['appeal_refuse_reason'] = input('appeal_refuse_reason');
            $info['appeal_refuse_time'] = date('Y-m-d H:i:s');
        }
        $result = Db::name('task_receive')->where(['id' => input('id')])->update($info);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        updateredis(config('xsurls') . '/job/updateredis', $uid);
        return outputJson(0, 'ok');
    }

    //新手任务页
    public function noobTask()
    {
        $this->dailyTasks($this->user['id']);

        //新手任务
        $info['inviteCode'] = $this->user['id'];
        $info['is_fill_invitecode'] = $this->user['invite_code'] ? 1 : 0;//是否填写邀请码
        $info['is_bind_mobile'] = $this->user['mobile'] ? 1 : 0;//是否绑定手机号


        $info['is_withdrawal'] = ($this->user['istixian'] == 1) ? 1 : 0;//是否完成一次提现

        $taskRelease = Db::name('task_release')->where(['uid' => $this->user['id'], 'status' => 2])->find();
        $info['is_task_release'] = $taskRelease ? 1 : 0;//是否完成一次任务发布
        $taskReceive = Db::name('task_receive')->where(['uid' => $this->user['id'], 'status' => 3])->find();
        $info['is_task_achieve'] = $taskReceive ? 1 : 0;//是否完成一次任务
        //日常任务
        $dailyTasks = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->find();
        $info['is_pangolin_ads'] = $dailyTasks['is_pangolin_ads'] ?? 0;
        $info['pangolin_ads_num'] = $dailyTasks['pangolin_ads_num'] ?? 0;
        $info['is_jd_goods'] = $dailyTasks['is_jd_goods'] ?? 0;
        $info['jd_goods_num'] = $dailyTasks['jd_goods_num'] ?? 0;
        $info['ifgame'] = $dailyTasks['ifgame'] ?? 0;
        $info['iftixian'] = $dailyTasks['iftixian'] ?? 0;
        $info['iferan'] = $dailyTasks['iferan'] ?? 0;
        //查询今日和累计赚取余额
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        $info['eran_money'] = $userEarn['todayearned'];

        //金币显示
        $info['account'] = [
            'invite_money' => 20000,
            'bind_mobile_money' => 20000,
            'withdrawal_money' => 20000,
            'task_release_money' => 20000,
            'task_achieve_money' => 20000,
            'pangolin_ads_money' => 10000,
            'jd_goods_money' => 10000,
            'ifgame_money' => 10000,
            'iftixian_money' => 10000,
            'iferan_money' => 10000,
        ];
        return outputJson(0, 'ok', $info);
    }


    //增加看视频和京东商品浏览次数
    public function addNum()
    {
        $dailyTasks = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->find();
        if ($dailyTasks) {
            if (input('type') == 1) {//增加浏览视频次数
                $r1 = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->setInc('pangolin_ads_num', 1);
                if ($r1 === false) {
                    return outputJson(100, 'fail');
                }
                if ($dailyTasks['pangolin_ads_num'] + 1 != 3) {
                    return outputJson(0, 'ok');
                }
                //日常任务----查看穿山甲广告次数
                $signin = dailyTasks(config('urls') . '/account/addaccount', '观看视频3次', $this->user['id'], 10);
                if (!$signin) {
                    return outputJson(100, 'fail');
                }
                $r2 = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->update(['is_pangolin_ads' => 1]);
                if ($r2 === false) {
                    return outputJson(100, 'fail');
                }
            }
            if (input('type') == 2) {//查看商品数
                $r1 = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->setInc('jd_goods_num', 1);
                if ($r1 === false) {
                    return outputJson(100, 'fail');
                }
                if ($dailyTasks['jd_goods_num'] + 1 != 10) {
                    return outputJson(0, 'ok');
                }
                //日常任务----浏览随机京东商品10次
                $signin = dailyTasks(config('urls') . '/account/addaccount', '浏览随机京东商品10次', $this->user['id'], 10);
                if (!$signin) {
                    return outputJson(100, 'fail');
                }
                $r2 = Db::name('daily_tasks')->where(['uid' => $this->user['id'], 'add_time' => date('Y-m-d')])->update(['is_jd_goods' => 1]);
                if ($r2 === false) {
                    return outputJson(100, 'fail');
                }
            }
        } else {
            if (input('type') == 1) {//增加浏览视频次数
                $r3 = Db::name('daily_tasks')->insert(['uid' => $this->user['id'], 'add_time' => date('Y-m-d'), 'pangolin_ads_num' => 1]);
                if (!$r3) {
                    return outputJson(100, 'fail');
                }
            }
            if (input('type') == 2) {//查看商品数
                $r3 = Db::name('daily_tasks')->insert(['uid' => $this->user['id'], 'add_time' => date('Y-m-d'), 'jd_goods_num' => 1]);
                if (!$r3) {
                    return outputJson(100, 'fail');
                }
            }
        }
        return outputJson(0, 'ok');
    }

    //日常任务
    private function dailyTasks($uid)
    {
        $dailyTasks = Db::name('daily_tasks')->where(['uid' => $uid, 'add_time' => date('Y-m-d')])->find();
        $info = [];
        if ($dailyTasks) {
            //查询今天没完成游戏
            $dailyjoblog = baseDailyTasks(config('urls') . '/account/dailyjoblog', $uid);
            //完成1次游戏赚钱任务
            if (!$dailyTasks['ifgame'] && $dailyjoblog['ifgame']) {
                //日常任务--完成1次游戏赚钱任务
                $signin = dailyTasks(config('urls') . '/account/addaccount', '完成1次游戏赚钱任务', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['ifgame'] = 1;
            }
            //邀请1名好友，好友完成提现才算
            if (!$dailyTasks['iftixian'] && $dailyjoblog['iftixian']) {
                //日常任务--邀请1名好友，好友完成提现才算
                $signin = dailyTasks(config('urls') . '/account/addaccount', '邀请1名好友，好友完成提现才算', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['iftixian'] = 1;
            }
            //今日累计赚到3元
            $userEarn = userBalance(config('urls') . '/account/getinfo', $uid);
            if (!$dailyTasks['iferan'] && $userEarn['todayearned'] > 3) {
                //日常任务--今日累计赚到3元
                $signin = dailyTasks(config('urls') . '/account/addaccount', '今日累计赚到3元', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['iferan'] = 1;
            }
            if ($info) {
                $result = Db::name('daily_tasks')->where(['uid' => $uid, 'add_time' => date('Y-m-d')])->update($info);
                if ($result === false) {
                    return false;
                }
            }
        } else {
            //查询今天没完成游戏
            $dailyjoblog = baseDailyTasks(config('urls') . '/account/dailyjoblog', $uid);
            //完成1次游戏赚钱任务
            if ($dailyjoblog['ifgame']) {
                //日常任务--完成1次游戏赚钱任务
                $signin = dailyTasks(config('urls') . '/account/addaccount', '完成1次游戏赚钱任务', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['ifgame'] = 1;
            }
            //邀请1名好友，好友完成提现才算
            if ($dailyjoblog['iftixian']) {
                //日常任务--邀请1名好友，好友完成提现才算
                $signin = dailyTasks(config('urls') . '/account/addaccount', '邀请1名好友，好友完成提现才算', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['iftixian'] = 1;
            }
            //今日累计赚到3元
            $userEarn = userBalance(config('urls') . '/account/getinfo', $uid);
            if ($userEarn['todayearned'] > 3) {
                //日常任务--今日累计赚到3元
                $signin = dailyTasks(config('urls') . '/account/addaccount', '今日累计赚到3元', $uid, 10);
                if (!$signin) {
                    return false;
                }
                $info['iferan'] = 1;
            }
            if ($info) {
                $info['uid'] = $uid;
                $info['add_time'] = date('Y-m-d');
                $result = Db::name('daily_tasks')->insert($info);
                if (!$result) {
                    return false;
                }
            }
        }
    }

}